<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>🛒</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    li {
      list-style: none;
    }

    .container {
      width: 400px;
      margin: 50px auto;
    }

    .container h1 {
      margin: 22px 0;
    }

    #shopping-form {
      margin-bottom: 30px;
    }

    #shopping-form label {
      display: block;
      font-weight: 500;
    }

    .add-box {
      display: flex;
      margin-top: 10px;
    }

    #item-name {
      width: 250px;
      padding: 12px 8px;
      background: #f2ecee;
      border: none;
      border-left: 7px solid #d9cfd3;
      border-radius: 3px;
      cursor: pointer;
      font-weight: 600;
      text-align: center;
      font-size: 16px;
      outline: none;
      flex-grow: 1;
    }

    ::placeholder {
      color: #d9cfd3;
    }

    .btn {
      font-size: 14px;
      font-weight: 600;
      padding: 10px 30px;
      border-radius: 3px;
      border: none;
      cursor: pointer;
      transition: background-color 0.2s ease;
      margin-left: 10px;
    }

    #btn-add {
      color: #fff;
      background-color: #1c6c9e;
    }

    #btn-add:hover {
      background-color: #1d465f;
    }

    #item-name:focus {
      border-color: #458179;
    }

    #shopping-list li {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
      justify-content: space-between;

    }

    #shopping-list p {
      text-indent: 10px;
      width: 270px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <div class="container">
    <h1>购物清单添加/删除</h1>
    <div id="shopping-form">
      <label for="item-name">消费名称</label>
      <div class="add-box">
        <input id="item-name" type="text" placeholder="输入购物名称">
        <button id="btn-add" class="btn">添加</button>
      </div>
    </div>

    <ul id="shopping-list">
    </ul>

  </div>

  <script>
    const itemName = document.querySelector('#item-name');
    const btnAdd = document.querySelector('#btn-add');
    const shoppingList = document.querySelector('#shopping-list');

    // 1、添加
    btnAdd.onclick = () => {
      shoppingList.insertAdjacentHTML('beforeend', `
        <li>
          <p>${itemName.value}</p>
          <button class="btn">删除</button>
        </li>
      `)
      itemName.value = '';

      // 2、删除
      // const btns = document.querySelectorAll('#shopping-list .btn')
      // for (let i = 0; i < btns.length; i++) {
      //   btns[i].onclick = function () {
      //     this.parentNode.remove()
      //   }
      // }
    }

    // 事件委托
    shoppingList.onclick = function (e) {
      if (e.target.tagName === 'BUTTON') {
        e.target.parentNode.remove()
      }
    }




  </script>

</body>

</html>